package com.ts.executor;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

/**
 * 基本线程池管理
 * 
 * @author jerry
 */
public class ExecutorServiceManager {
	private final static Logger logger = Logger
			.getLogger(ExecutorServiceManager.class);

	private static ExecutorServiceManager instance = new ExecutorServiceManager();

	/**
	 * 单例实现
	 */
	private ExecutorServiceManager() {
	}

	public static ExecutorServiceManager getInstance() {
		return instance;
	}

	/**
	 * 用于保存数据的线程池 核心线程数10个 最大线程数12个 等待时间20秒, 
	 * 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序
	 * com.ts.executor.ExecutorServiceManager.MyExecutorForDBRejectedExecutionHandler
	 */
	private ThreadPoolExecutor executorforDB;

	public void init() {
		/****/
		this.executorforDB = new ThreadPoolExecutor(10, 12, 20,
				TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000),
				new MyExecutorForDBRejectedExecutionHandler());
	}

	public class MyExecutorForDBRejectedExecutionHandler implements
			RejectedExecutionHandler {
		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			logger.error("保存数据处理时出现延时导致线程堵塞请检查数据库连接");
			logger.error(r.toString());
		}
	}
	
	public ThreadPoolExecutor getExecutorforDB() {
		return executorforDB;
	}
}
